﻿define([
// Dojo
        "dojo/_base/connect",
        "dojo/_base/lang",
        "dojo/_base/declare",
        "dojo/html",
        "dojo/dom-construct",
        "dojo/dom-style",
        "dojo/dom-attr",
// Dijit
        "dijit/_TemplatedMixin",
        "dijit/_WidgetBase",
        "dijit/_WidgetsInTemplateMixin",
        "epi/shell/command/_WidgetCommandProviderMixin",
        "dojo/dnd/Source",
//CMS
        "epi-cms/_ContentContextMixin",
        "epi-cms/widget/MultipleFileUpload",
        "epi/dnd/Target",
        "epi/shell/command/_Command",
        "epi/shell/widget/dialog/Dialog",

        "epi/shell/command/_CommandProviderMixin",
        "epi-cms/widget/ContextMenu",

        "epi-cms/legacy/LegacyDialogPopup",
        "epi-cms/widget/_HasChildDialogMixin",

        "ow-epi-imageBrowser/knockout-2.2.1",
        "ow-epi-imageBrowser/ImageBrowserViewModel",
        "dojo/text!./imageBrowserWidgetTemplate.htm",
        "epi/i18n!epi-cms/nls/episerver.cms.widget.uploadmultiplefiles.uploadform",
        "xstyle/css!./ImageBrowserWidget.css"
    ], function (
    // Dojo
        connect,
        lang,
        declare,
        html,
        domConstruct,
        domStyle,
        domAttr,
    // Dijit
        _TemplatedMixin,
        _WidgetBase,
        _WidgetsInTemplateMixin,
        _WidgetCommandProviderMixin,
        DndSource,
    //CMS
        _ContentContextMixin,
        MultipleFileUpload,
        DndTarget,
        _Command,
        Dialog,

        _CommandProviderMixin, //used as constructor not as mixin
        ContextMenu,

        LegacyDialogPopup,
        _HasChildDialogMixin,

        ko,
        VirtualPathProvidersViewModel,
        template,
        resources
    ) {
        return declare("ow-epi-imageBrowser.imageBrowserWidget",
            [_WidgetBase, _TemplatedMixin, _ContentContextMixin, _WidgetsInTemplateMixin, _WidgetCommandProviderMixin, _HasChildDialogMixin], {

                allowDragItems: true,

                allowSelectItems: false,

                postMixInProperties: function () {
                    this.inherited(arguments);
                },

                postCreate: function () {
                    // call base implementation
                    this.inherited(arguments);

                    if (!this.vppListing) {
                        alert('vpp not defined');
                        return;
                    }

                    if (!this.fileControllerUrl) {
                        alert('fileControllerUrl not defined');
                        return;
                    }

                    this.viewModel = new VirtualPathProvidersViewModel(this.fileControllerUrl, this.vppListing, this.currentContext.id, this.allowSelectItems, this.reloadVppAtStart);
                    this.viewModel.onMenuClick = this._showContextMenu;
                    this.viewModel.imageBrowserWidget = this;

                    ko.applyBindings(this.viewModel, this.imageBrowserContainer);

                    if (this.allowDragItems) {
                        var self = this;
                        this.viewModel.currentVpp.imageFiles.subscribe(function (value) {
                            self.mySource.sync();
                        });
                        this.viewModel.currentVpp.touchDirectory.subscribe(function () {
                            self.mySource.selectNone();
                        });

                        this.mySource = new DndSource(this.itemsList, {
                            //creator: lang.hitch(this, this._dndSourceItemCreator),
                            copyOnly: true,
                            selfAccept: false,
                            selfCopy: false,
                            accept: []
                        });
                    }
                },

                postMixInProperties: function postMixInPropertiesF() {
                    this.inherited(arguments);

                    var self = this;

                    var AddFolderCommand = declare([_Command], {
                        label: 'New folder',
                        canExecute: true,
                        iconClass: 'image-browser-new-folder',
                        _execute: function () {
                            if (!self.viewModel.isInNewDirectoryMode()) {
                                self.viewModel.createNewDirectoryInCurrentVpp();
                            }
                        }
                    });

                    var AddFileCommand = declare([_Command], {
                        label: 'Add file',
                        canExecute: true,
                        iconClass: 'image-browser-new-file',
                        _execute: function () {
                            self.showUploadForm(null);
                        }
                    });

                    this.commands = [new AddFolderCommand(), new AddFileCommand()];
                },

                templateString: template,

                contextChanged: function (context, callerData) {
                    this.inherited(arguments);

                    if (this.viewModel && this.currentContext.id) {
                        this.viewModel.changeContext(context.id);
                    }
                },

                getImageSelection: function () {
                    if (!this.viewModel) {
                        return null;
                    }
                    var selectedImage = this.viewModel.currentVpp.imageSelection.selectedImage();
                    if (selectedImage) {
                        return selectedImage.path();
                    }
                    return null;
                },

                selectByPath: function (fileName) {
                    if (!this.viewModel) {
                        return null;
                    }
                    this.viewModel.setVppByPath(fileName);
                },

                //
                // code copied from:
                // epi.cms.component.FileManagement
                showUploadForm: function (files) {
                    var uploader = new MultipleFileUpload();

                    var uploadDialog = new Dialog({
                        title: resources.addfiles,
                        content: uploader,
                        defaultActionsVisible: false,
                        closeIconVisible: false
                    });

                    uploader.on("beforeUploaderChange", lang.hitch(this, function () {
                        //this._uploading = true;
                    }));

                    // Reload current folder of File manager, to reflect changes
                    uploader.on("uploadComplete", lang.hitch(this, function () {
                        this.viewModel.currentVpp.refreshList();

                        if (uploadDialog && !uploadDialog.open) {
                            uploadDialog.destroy();
                        }

                        //this._uploading = false;
                    }));

                    // close multiple files upload dialog when stop uploading
                    uploader.on("close", lang.hitch(this, function (uploading) {
                        if (uploadDialog) {
                            if (uploading) {
                                uploadDialog.hide();
                            } else {
                                uploadDialog.destroy();
                            }
                        }
                    }));

                    // only show close button for multiple files upload dialog
                    uploadDialog.definitionConsumer.add({
                        name: "close",
                        label: epi.resources.action.close,
                        action: function () {
                            uploader.close();
                        }
                    });

                    uploadDialog.resize({ w: 700 });

                    uploadDialog.show();

                    //uploader.set("breadcrumb", this.get("breadcrumbParts"));
                    uploader.set("uploadDirectory", this.viewModel.currentVpp.directoryPath());

                    // upload files on drop or on click "Add Files" toolbar icon
                    uploader.upload(files);
                },


                _contextMenu: null,
                _contextMenuCommandProvider: null,

                _showContextMenu: function (imageBrowserWidget /* this */, imageFile, evt) {
                    if (!this._contextMenu) {
                        this._contextMenu = new ContextMenu({ leftClickToOpen: true });


                        var AddFolderCommand = declare([_Command], {
                            label: 'Open file',
                            canExecute: true,
                            iconClass: 'menu-preview',
                            _execute: function () {
                                this.model.preview();
                            }
                        });

                        var AddFileCommand = declare([_Command], {
                            label: 'Edit',
                            canExecute: true,
                            //iconClass: 'menu-edit',
                            _execute: function () {
                                this.model.edit();
                            }
                        });

                        var EditFileSummary = declare([_Command], {
                            label: 'Edit fileSummary',
                            canExecute: true,
                            //iconClass: '',
                            _execute: function () {
                                imageBrowserWidget._showFileSummaryDialog.call(imageBrowserWidget, this.model);
                            }
                        });

                        var DeleteFile = declare([_Command], {
                            label: 'Delete',
                            canExecute: true,
                            iconClass: 'menu-rename',
                            _execute: function () {
                                this.model.deleteFile();
                            }
                        });

                        var RenameFile = declare([_Command], {
                            label: 'Rename',
                            canExecute: true,
                            iconClass: 'menu-delete',
                            _execute: function () {
                                this.model.renameFile();
                            }
                        });

                        this._contextMenuCommandProvider = new _CommandProviderMixin();
                        this._contextMenuCommandProvider.commands = [new EditFileSummary(), new AddFolderCommand(), new AddFileCommand(),
                            new DeleteFile(), new RenameFile()];
                        this._contextMenu.addProvider(this._contextMenuCommandProvider);

                        dojo.addClass(this._contextMenu.domNode, "image-browser");

                        //connect.connect(this._contextMenu, "onClose", this, "_onContextMenuClose");
                        //connect.connect(this._contextMenu, "onOpen", this, "_onContextMenuOpen");
                    }

                    //Bind the item
                    this._contextMenuCommandProvider.updateCommandModel(imageFile);

                    //Open the context menu
                    this._contextMenu.scheduleOpen(evt.target, null, { x: evt.pageX, y: evt.pageY });
                },


                _dialog: null,

                _showFileSummaryDialog: function (imageFile) {
                    if (!this._dialog) {
                        var params = {
                            autoFit: false,
                            features: {
                                width: 800,
                                height: 400
                            },
                            //url: '/EditFileSummary.aspx?filename=' + imageFile.path()
                            url: this.fileSummaryDialogUrl + '?filename=' + imageFile.path()
                        };

                        this._dialog = new LegacyDialogPopup(params);

                        this.connect(this._dialog, "onCallback", this._onDialogCallback);
                        this.connect(this._dialog, 'onHide', this._onDialogHide);
                    }

                    this.isShowingChildDialog = true;

                    this._dialog.show();
                },

                _onDialogCallback: function (value) {

                    return;
                },

                _onDialogHide: function () {
                    this.isShowingChildDialog = false;

                    this._dialog.destroyRecursive();
                    delete this._dialog;
                }

            });
    });